package com.example.firstprojectnew.service;

import com.example.firstprojectnew.entity.User;
import com.example.firstprojectnew.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Author: lihua
 * @Date: 2025/4/25 16:23
 * @Version: v1.0.0
 * @Description:
 **/
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.getUserById(username);
        if(user == null){
            throw new UsernameNotFoundException("用户不存在！");
        }
        UserDetails userDetail = org.springframework.security.core.userdetails.User.builder()
                .username(username)
                .password(new BCryptPasswordEncoder().encode(user.getUserPhone()))
                .authorities("ROLE_student")
                .roles(user.getRole()).build();
        return userDetail;
    }


}
